/**
 * Created by 55456 on 2016/4/8.
 */
var Login = require("../../controllers/LoginController");
var Register = require("../../controllers/RegisterController");
var codeConfig = require("../../configs/codeConfig");
var db = require("../../models/index");
var utilx = require("../../lib/util");
var cache = require("../../instances/cache");

module.exports = (router) => {
    var User = db.models.User;

    router.post("/api/login", function *() {
        this.checkBody("mobile").notEmpty();
        this.checkBody("password").notEmpty();
        if (this.errors) {
            this.body = codeConfig.parseErrorMsg(this.errors);
            return;
        }
        var body = this.request.body;
        var result = yield  Login.login(this, User, {mobile: body.mobile}, {password: body.password});
        this.body = result ? codeConfig.parseMsg(result) : codeConfig.parseErrorMsg();
    });

    router.post("/api/register", function *() {
        //todo:add avatar validate
        this.checkBody("mobile").notEmpty();
        this.checkBody("password").notEmpty();
        this.checkBody("userName").notEmpty();
        this.checkBody("avatar").notEmpty();
        if (this.errors) {
            this.body = codeConfig.parseErrorMsg(this.errors);
            return;
        }
        var body = this.request.body;
        var token = utilx.getToken(body.mobile + body.password);
        var user = {
            mobile: body.mobile,
            password: body.password,
            userName: body.userName,
            avatar: body.avatar,
            token: token
        };
        try {
            var result = yield Register.register(this, User, user);
        } catch (err) {
            console.log("register fail,account has been exist");
            result = null;
        }
        this.body = result ? codeConfig.parseMsg(result) : codeConfig.parseErrorMsg("do not have this user");
    });

    router.post("/api/getToken", function *() {
        this.checkBody("token").notEmpty();
        if (this.errors) {
            this.body = codeConfig.parseErrorMsg(this.errors);
            return;
        }
        var body = this.request.body;
        var token = body.token;
        var user = yield User.findOne({
            where: {
                token: token
            }
        });
        var result = yield  Login.login(this, User, {mobile: user.mobile}, {password: user.password});
        this.body = result ? codeConfig.parseMsg(result) : codeConfig.parseErrorMsg("token is wrong,can not get LoginToken");
    });

    router.get("/api/debugLogin", function *() {
        //todo:delete this when the app publish
        var user = yield User.findOne({
            where:{
                id:1
            }
        });
        this.body = user.token;
    });
};
